<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col>
          <span>选择商品分类</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader :options="cateList" :props="props" v-model="selectedKeys" @clear="clearChange"
            @change="handleChange" clearable filterable placeholder="请选择商品分类">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- Tab标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="ifBtnshow" @click="addParamsDialogVisible = true">添加参数</el-button>
          <!-- 表格视图 -->
          <el-table :data="manyList" border style="width: 100%">
            <!-- 展开行 -通过插槽形式-->

            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{ item }}</el-tag>
                <el-input>
                  <template slot="prepend">添加tag</template>
                  <el-button slot="append" icon="el-icon-plus" @click="addParamsDialogVisible = true"></el-button>
                </el-input>



              </template>
            </el-table-column>


            <!-- 索引列 -->
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <!-- 属性名称列 -->
            <el-table-column prop="attr_name" label="参数名称" width="120"></el-table-column>
            <!-- 操作列 -->
            <el-table-column prop="attr_id" label="操作" width="280">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" @click="delParams(scope.row.attr_id)">删除</el-button>
                <!-- @click="delParams(scope.row.attr_id)" -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="ifBtnshow" @click="addParamsDialogVisible = true">添加属性</el-button>
          <!-- 表格视图 -->
          <el-table :data="onlyList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <!-- 属性名称列 -->
            <el-table-column prop="attr_name" label="属性名称" width="120"></el-table-column>
            <!-- 操作列 -->
            <el-table-column prop="attr_id" label="操作" width="280">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" @click="delParams(scope.row.attr_id)">删除</el-button>
                <!-- @click="delParams(scope.row.attr_id)" -->
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + textTitle" :visible.sync="addParamsDialogVisible" width="50%" @close="closeDialog">
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="80px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改' + textTitle" :visible.sync="editParamsDialogVisible" width="50%" @close="closeDialog">

      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="80px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeParams">修改</el-button>
      </span>
    </el-dialog>
    <!-- 删除对话框界面 -->
    <el-dialog title="提示" :visible.sync="delDialogVisible" width="30%">
      <span>确定要删除吗?</span>
      <span slot="footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clearParams">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: 'WorkspaceJsonParams',

  data () {
    return {
      cateList: [],
      // props配置项
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true,
      },
      //级联选择器的选中项
      selectedKeys: [],
      //被激活的标签页的名称
      activeName: 'many',
      //动态参数列表
      manyList: [],
      //静态属性列表
      onlyList: [],
      //添加参数对话框的显示和隐藏
      addParamsDialogVisible: false,
      editParamsDialogVisible: false,
      delDialogVisible: false,

      //添加参数的表单数据对象
      addParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: '',
      },
      //修改参数的表单数据对象
      editParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: '',

      },
      //删除参数的表单数据对象
      delParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: '',

      },

      //表单校验规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },







    };

  },
  created () {

    this.getCateList()
  },

  mounted () {

  },

  methods: {
    //获取所有商品分类
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 3
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 级联选择器的选中项发生变化时触发
    handleChange () {
      if (this.selectedKeys.length === 3) {
        this.$message({
          type: 'success',
          message: '获取参数列表成功',
        })
      } else {

        this.clearChange()
      }

      this.getParamsList()

    },
    // 获取参数列表数据,公共函数
    getParamsList () {
      if (this.selectedKeys.length == 0) return console.log('请选择分类');
      console.log(this.activeName);
      // 根据分类id获取参数列表
      this.$http.get(`categories/${this.selectedKeys[2]}/attributes`, {
        params: {
          sel: this.activeName
        }
      }).then(res => {
        // console.log(res.data.data)
        if (res.data.meta.status !== 200) return this.$message.error('获取参数列表失败')
        // 循环遍历每一项的attr_vals属性,将其转换为数组
        res.data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        // console.log(res.data.data)

        if (this.activeName === 'many') {
          this.manyList = res.data.data
        } else {
          this.onlyList = res.data.data
        }

      })
    },



    // Tab标签页点击事件
    handleClick () {
      // console.log(this.activeName)
      //只有设置分类后才能获取参数列表
      if (this.selectedKeys.length !== 3) return this.$message.error('请先选择分类')
      this.getParamsList()
    },
    //对话框关闭时重置表单
    closeDialog () {
      //重置表单
      this.$refs.addParamsFormRef.resetFields()
    },
    //发送post请求添加参数
    addParams () {
      // console.log(this.addParamsForm)  
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.selectedKeys[2]}/attributes`,
          { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addParamsDialogVisible = false
        this.getParamsList()
      })
    },

    //点击修改按钮时触发
    async editParams (id) {
      this.editParamsDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.selectedKeys[2]}/attributes/${id}`, { attr_sel: this.activeName })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      this.editParamsForm = res.data

    },
    //确定修改动态参数
    changeParams () {
      // console.log(this.editParamsForm)  
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.selectedKeys[2]}/attributes/${this.editParamsForm.attr_id}`,
          { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editParamsDialogVisible = false
        this.getParamsList()
      })

    },
    //当点击清除按你的时候  重新发起请求
    clearChange () {
      this.selectedKeys = [],
        this.manyList = [],
        this.onlyList = [],
        this.$message({
          type: 'error',
          message: '请重新选择分类',
        })
    },
    //点击删除时触发
    delParams (id) {
      // 获取参数数据
      this.$http.get(`categories/${this.selectedKeys[2]}/attributes/${id}`, { attr_sel: this.activeName }).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取参数失败')
        this.delParamsForm = res.data.data
      })
      this.delDialogVisible = true

    },
    // 提交删除请求
    clearParams () {
      this.$http.delete(`categories/${this.selectedKeys[2]}/attributes/${this.delParamsForm.attr_id}`).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.delDialogVisible = false
        this.getParamsList()
      })
    },

    //方法结尾
  },
  //计算属性判断按钮是否显示
  computed: {
    ifBtnshow () {
      if (this.selectedKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    //计算标题文本
    textTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },



  }





  //结尾
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 20px 0
}
</style>